package com.fuershiye.woman.monitor.controller;

import com.fuershiye.woman.monitor.beans.*;
import com.fuershiye.woman.monitor.constants.Massage;
import com.fuershiye.woman.monitor.constants.ReportType;
import com.fuershiye.woman.monitor.constants.StringLockPrefix;
import com.fuershiye.woman.monitor.model.DepartIndicator;
import com.fuershiye.woman.monitor.model.Department;
import com.fuershiye.woman.monitor.model.FormsDepart;
import com.fuershiye.woman.monitor.model.Indicator;
import com.fuershiye.woman.monitor.service.*;
import com.fuershiye.woman.monitor.utils.DateFormatUtil;
import com.fuershiye.woman.monitor.utils.MyUtilString;
import com.fuershiye.woman.monitor.utils.ReportUtil;
import com.google.common.collect.Interner;
import com.google.common.collect.Interners;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 报表管理
 * 
 * @author yongyongdong
 *
 */
@Controller
@RequestMapping(value = "/report")
public class ReportController {

	private static final Logger logger = LoggerFactory
			.getLogger(ReportController.class);

	@Autowired
	FormsDepartService formsDepartService;
	@Autowired
	IndicatorService indicatorService;
	@Autowired
	DepartmentService departmentService;
	@Autowired
	DepartIndicatorService departIndicatorService;
	@Autowired
	ReportService reportService;
	@Autowired
	UserService userService;


	/**
	 * @param year 【必传，用英文逗号隔开的年份  2011,2012,2013】
	 * @return	返回值是value_color
	 *
	 * 适用场景【自己查看自己上报的情况】
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	//	@RequiresPermissions("report:preAlarm")
	@RequestMapping(value = "/self/list.do")
	@ResponseBody
	public Result self(Long formsid, Integer year, String indicatorTypeIds) {

		if(!DateFormatUtil.isYear(year)||formsid==null||formsid==0) {
			return new Result(Massage.ERROR_PARAMETER);
		}

		String uname = SecurityUtils.getSubject().getPrincipal() + "";
		Department department = userService.getDepartIdByName(uname);
		if (department == null) {
			logger.error("Error in ReportController user department is null, uname is {}", uname);
			return  new Result(Massage.DEPART_IS_NULL);
		}

		List<Long> types = MyUtilString.str2LongByPlaceHolder(indicatorTypeIds, ",");
		List<Indicator> indicatorList =	indicatorService.listByCondition("", formsid, types, null, null, 1,null);
		List<Long> indicators = indicatorService.getIndicatorId(indicatorList);
		List<Long> departIds = Lists.newArrayList();
		departIds.add(department.getId());

		// 获取近两年的数据
		List<Integer> yearList = Lists.newArrayList(year);
		List<ViewReportAllValue> yearReportList = reportService.getReportDate(departIds, formsid, indicators, yearList, 1);
        //补充指标名称，可能需要拼接父指标名称
        yearReportList = reportService.appendPidName(yearReportList);
		List<Map<String, Object>> yearResult = reportService.filter(yearReportList, yearList);

		List<Integer> lastYearList = Lists.newArrayList(year-1);
		List<ViewReportAllValue> lastReportList = reportService.getReportDate(departIds, formsid, indicators, lastYearList, 1);
		List<Map<String, Object>> lastResult = reportService.filter(lastReportList, lastYearList);

		List<Map<String, Object>> mergeResult = reportService.merge(yearResult, lastResult, year);

		List<Map<String, Object>> result = Lists.newArrayList();
		for (int i = 0; i < mergeResult.size(); i++) {
			Map<String, Object> map = mergeResult.get(i);
			for (int j = 0; j < yearList.size(); j++) {
				int yearOne = yearList.get(j);
				if(map.containsKey(yearOne+"")){
					String valueYear = map.get(yearOne+"").toString();
					if(!valueYear.isEmpty()){
//						valueYear = 数据上报的类型_每年的目标值_数值_显示数据展示时效果的规则_每年的备注
						String rtype = valueYear.split("_",-1)[0];
						String value = valueYear.split("_",-1)[2];
						String remark = valueYear.split("_",-1)[4];
						if(value!=null && value.equals("0.0")){
							map.put(yearOne+"", "0");
						} else {
							//TODO
							map.put(yearOne+"", value);
						}
						if(!StringUtils.isEmpty(rtype)){
							map.put("rtype", rtype);
							// 塞默认值 1，默认是数值类型
						}else if(map.containsKey("rtype") && StringUtils.isEmpty(map.get("rtype"))){
							map.put("rtype", "1");
						}
						map.put("remark", remark==null?"":remark);
					}
				}
			}
			result.add(map);
		}

		return new Result(Massage.SUCCESS, new PageResult(result, result.size()));
	}

	/**
	 * @param departid 数据的来源部门
	 * @param formsid
	 * @param aimids 复制给的目标部门
	 * @return
	 *
	 * 适用场景【自己查看自己上报的情况】
	 */
	@RequestMapping(value="/copy.do")
	@ResponseBody
	public Result copy(Integer year, Long departid, Long formsid, String aimids, String editor) {

		if(formsid==null||formsid==0 || !DateFormatUtil.isYear(year)
				|| departid==null||departid==0 || StringUtils.isEmpty(aimids)){
			logger.error("FormsDepartController copy error:"
					+",year:"+year
					+",formsid:"+formsid
					+",departid:"+departid
					+",aimids:"+aimids
			);
			return new Result(Massage.ERROR_PARAMETER);
		}

		List<Long> aimidList = MyUtilString.str2LongByPlaceHolder(aimids, ",");
		if(aimidList.isEmpty()||aimidList.size()<1){
			return new Result(Massage.ERROR_PARAMETER);
		}
		List<Long> departids = Lists.newArrayList(departid);
		//加锁避免实现单点系统的并发操作
		Interner<String> pool = Interners.newWeakInterner();
		synchronized (pool.intern(StringLockPrefix.LOCK_COPY_DEPART_FORMS+departid+formsid)){

			for (Long aimDepart : aimidList) {

				Department aimdepartment = departmentService.get(aimDepart);
				if(aimdepartment==null){
					logger.error("Report copy error,depart id:"+aimDepart);
					continue;
				}
				// 找from 部门的数据
				List<ViewDepartIndicatorReport> listDepartIndicator = departIndicatorService.listByCondition(departids, formsid, null, year, 1, null);
				for (ViewDepartIndicator fromDeptIndctor : listDepartIndicator) {
					if(fromDeptIndctor==null){
						continue;
					}
					// 找 m目标部门的数据
					DepartIndicator aimDepartIndicator = departIndicatorService.findByCondition(aimDepart, fromDeptIndctor.getForms(), fromDeptIndctor.getIndicator(), year, 1);
					if(aimDepartIndicator==null){
						aimDepartIndicator = new DepartIndicator();
						aimDepartIndicator.setDepartid(aimDepart);
						aimDepartIndicator.setForms(fromDeptIndctor.getForms());
						aimDepartIndicator.setIndicator(fromDeptIndctor.getIndicator());
						aimDepartIndicator.setRtype(1);
						aimDepartIndicator.setYear(year);
						aimDepartIndicator.setCtime(new Date());
						aimDepartIndicator.setMtime(new Date());
						aimDepartIndicator.setStatus(1);
						aimDepartIndicator.setEditor(ReportUtil.getEditor(editor));
					}
					aimDepartIndicator.setMtime(new Date());
					aimDepartIndicator.setStatus(1);
					aimDepartIndicator.setEditor(ReportUtil.getEditor(editor));

					departIndicatorService.save(aimDepartIndicator);
				}
			}
		}

		return new Result(Massage.SUCCESS);
	}


	/**
	 * 上报属性的设置，并不一定真正的上报数据
	 * 
	 * @param id
	 * @param request
	 * @return
	 */
//	@RequiresPermissions("report:save")
	@RequestMapping(value = "/save.do")
	@ResponseBody
	public Result save(Long id, HttpServletRequest request) {

		//必须的参数
		String did = request.getParameter("departid");
		String fid = request.getParameter("formsid");
		String iids = request.getParameter("indicatorid");
		String yearStr = request.getParameter("year");
        String editor = request.getParameter("editor");

		if(MyUtilString.isBlankNull(did)
				|| MyUtilString.isBlankNull(fid)
				|| MyUtilString.isBlankNull(iids) || !DateFormatUtil.isYear(yearStr)
				){
			return new Result(Massage.ERROR_PARAMETER);
		}
		int year = Integer.parseInt(yearStr);
		//非必须参数
		String value = request.getParameter("value");
		String remark = request.getParameter("remark");
		String typeStr = request.getParameter("type");

		/** 假如有值则一定有类型 */
		if(!MyUtilString.isBlankNullZero(value)
				&& !ReportType.containId(typeStr)){
			return new Result(Massage.ERROR_PARAMETER);
		}

		/** 如果没有类型，不管有没有值，直接塞默认的上报数据类型 */
		int type = ReportType.DATA.getId();
		if(ReportType.containId(typeStr)){
			type = Integer.parseInt(typeStr);
		}

		long departid = Long.parseLong(did);
		long formsid = Long.parseLong(fid);
		List<Long> indicatorids = MyUtilString.str2LongByPlaceHolder(iids,",");

			int count=0;
			for (Long indicatorid : indicatorids) {

			Indicator indicator = indicatorService.get(indicatorid);
			if(indicator==null){
				return new Result(Massage.INDICATOR_IS_NULL);
			}

			DepartIndicator departIndicator= null;
			//用户想更新数据
			if(id != null && id != 0){
				//根据 ID 查询结果
				departIndicator = departIndicatorService.get(id);
				if(departIndicator==null){
					return new Result(Massage.REPORT_IS_NULL);
				}
			}else{
				//根据索引查询结果
				departIndicator = departIndicatorService.findByCondition(departid, formsid, indicatorid, year, null);
			}

			//更新数据，是否是新增
			if(departIndicator==null){
				departIndicator = new DepartIndicator();
				departIndicator.setCtime(new Date());
				Department department = departmentService.get(Long.valueOf(departid));
				if(department==null){
					return new Result(Massage.DEPART_IS_NULL);
				}
			}
			departIndicator.setDepartid(departid);
			departIndicator.setForms(formsid);
			departIndicator.setIndicator(indicatorid);
			departIndicator.setYear(year);
			departIndicator.setMtime(new Date());
			departIndicator.setStatus(1);
			departIndicator.setEditor(ReportUtil.getEditor(editor));

			departIndicatorService.save(departIndicator);
			departIndicator = departIndicatorService.findByCondition(departid, formsid, indicatorid, year, 1);

			if(departIndicator.getId()==null){
				return new Result(Massage.REPORT_FORM_DEPART_NULL);
			}

			Double valueDoube = null;
			if (!MyUtilString.isBlankNullZero(value)) {
				valueDoube = Double.valueOf(value);
			}

			Result result = reportService.saveReport(departIndicator.getId(), year, type, valueDoube, editor, remark);

			if(result.isSuccess()){
				count++;
			}
		}

		if(count==indicatorids.size()){
			return new Result(Massage.SUCCESS);
		}else if(count==0){
			logger.error("report save miss some one, the aim:"+indicatorids.size()+" but real is:"+count);
			return new Result(Massage.FAIL);
		}else {
			logger.error("report save miss some one, the aim:"+indicatorids.size()+" but real is:"+count);
			return new Result(Massage.SUCCESS);
		}
	}
	
//	@RequiresPermissions("report:delete")
	@RequestMapping(value = "/delete.do")
	@ResponseBody
	public boolean delete(Long id) {

		if(id==null||id==0){
			return false;
		}
		DepartIndicator departIndicator = departIndicatorService.get(id);
		if(departIndicator==null){
			return false;
		}
		departIndicator.setMtime(new Date());
		departIndicator.setStatus(0);
		departIndicator.setEditor(ReportUtil.getEditor(""));
		departIndicatorService.save(departIndicator);
		return true;
	}

	//单个年份的数值的上报或修改
//	@RequiresPermissions("reportSave:one")
	@SuppressWarnings("rawtypes")
	@RequestMapping(value = "/save/all.do")
	@ResponseBody
	public Result list(Long formsid, Long departid, Integer year, String editor, String values) {

		List<Map<String, Object>> result = null;
		if (formsid == null || formsid == 0 || departid == null || departid == 0
				|| !DateFormatUtil.isYear(year)||StringUtils.isEmpty(values)) {
			return new Result(Massage.ERROR_PARAMETER);
		}

		FormsDepart formsDepart = formsDepartService.findByDepartYearForms(departid, year, formsid);
		if(formsDepart==null){
			return new Result(Massage.REPORT_FORM_DEPART_NULL);
		}
		if(formsDepart.getStatus()==5){
			return new Result(Massage.REPORT_FINISHED);
		}

		//哪怕上报一条也变为上报中
		//0:删除(默认),1:未上报(一个指标都没有上报);2:上报中(部分上报);3:审核(自己审核);4:审核(上级部门);5:审核通过(不允许修改);6:其他;
		formsDepart.setStatus(2);
		if (!StringUtils.isEmpty(editor)){
			formsDepart.setEditor(editor);
		}
		formsDepartService.save(formsDepart);

		String[] idValues =  values.trim().split(";");
		if(idValues.length<1){
			return new Result(Massage.ERROR_PARAMETER);
		}
		for (int i=0; i<idValues.length; i++){

			String idValue = idValues[i];
			if(StringUtils.isEmpty(idValue)){
				continue;
			}
			/**
			 * rows[i].id+","+rows[i].type+","+rowsValue+","+rowsBase+";";
			 * */
			String [] idName = idValue.split(",", -1);
			if(idName.length!=4){
				return new Result(Massage.REPORT_VALUE);
			}
			try {
				long diid =Long.parseLong(idName[0]);
				String typeStr =idName[1];
				if(!ReportType.containId(typeStr)){
					return new Result(Massage.REPORT_TYPE);
				}
				int type = Integer.parseInt(typeStr);
				Double value = ReportType.getValueByType(type, idName[2]);
				String remark =idName[3];

				Result step= reportService.saveReport(diid, year, type, value, editor, remark);
				if(!step.isSuccess()){
					Map<String, Object> map = Maps.newHashMap();
					map.put("code",step.getCode());
					map.put("massage",step.getMassage());
					map.put("data",step.getData());
					result.add(map);
					logger.error("Report save all error, id:"+diid+",year:"+year+",value:"+value);
				}

			}catch (Exception e){
				logger.error(e.getMessage());
			}
		}

		if(result==null){
			return new Result(Massage.SUCCESS);
		}else{
			return new Result(Massage.SUCCESS, new PageResult(result, result.size()));
		}

	}

}
